package com.mediastory.spsserver.category.service.impl;

import java.io.File;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.mediastory.spsserver.category.dao.CategoryDao;
import com.mediastory.spsserver.category.domain.Category;
import com.mediastory.spsserver.category.service.CategorySvc;
import com.mediastory.spsserver.content.domain.Content;
import com.Ostermiller.util.Base64;

@Service
@Transactional
public class CategorySvcImpl implements CategorySvc {

	@Autowired
	private MessageSourceAccessor messages;
	
	@Autowired
	CategoryDao categoryDao;
	
	public CategorySvcImpl() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public List<Category> findbyList(Map<String, Object> condition)
			throws Exception {
		// TODO Auto-generated method stub
		return (List<Category>) (categoryDao.SelectList(condition));
	}

	@Override
	public Map<String, Object> findbyListPaging(Map<String, Object> condition)
			throws Exception {
		// TODO Auto-generated method stub
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("categoryList", (List<Category>) (categoryDao.SelectList(condition)));
		resultMap.put("categoryListTotalCnt", (Integer) (categoryDao.SelectListTotalCnt(condition)));
		
		return resultMap;
	}

	@Override
	public Category findby(Integer id) throws Exception {
		// TODO Auto-generated method stub
		return categoryDao.select(id);
	}

	@Override
	public Category add(Category category) throws Exception {
		// TODO Auto-generated method stub
		
		Category result = null;
		File file = null;
		try {
			//파일 업로드
			MultipartFile logoFile = category.getLogoFile();
			if(logoFile != null && ! logoFile.isEmpty() && logoFile.getContentType().contains("image")){
				long time = Calendar.getInstance().getTimeInMillis();
				String prefixNm = Base64.encode((URLEncoder.encode(category.getName(),"utf-8")+Long.toString(time)));
				//업로드 경로
				String uploadDir = messages.getMessage("file.category.uploadDir");
				//viewUrl
				String viewUrl = messages.getMessage("file.category.viewUrl");
				
				String fileNm = prefixNm + "."+(logoFile.getOriginalFilename()).split("\\.")[1];

				file = new File(uploadDir+fileNm);
				String url = viewUrl+fileNm;
				category.setLogoUrl(url);
				
				if(! file.isDirectory()){	//해당 폴더가 없을 경우 폴더 생성
					new File(uploadDir).mkdirs();
				}
				logoFile.transferTo(file);
			}
			
			result = categoryDao.insert(category);	
		} catch (Exception e) {
			// TODO: handle exception
			
			//업로드 파일 삭제
			if(file != null){
				file.delete();
			}
			
			throw e;
		}
		
		return result;
	}

	@Override
	public Category modify(Category category) throws Exception {
		// TODO Auto-generated method stub
		
		File file = null;
		try {
			//파일 업로드
			MultipartFile logoFile = category.getLogoFile();
			if(logoFile != null && ! logoFile.isEmpty() && logoFile.getContentType().contains("image")){
				long time = Calendar.getInstance().getTimeInMillis();
				String prefixNm = Base64.encode((URLEncoder.encode(category.getName(),"utf-8")+Long.toString(time)));
				//업로드 경로
				String uploadDir = messages.getMessage("file.category.uploadDir");
				//viewUrl
				String viewUrl = messages.getMessage("file.category.viewUrl");
				
				String fileNm = prefixNm + "."+(logoFile.getOriginalFilename()).split("\\.")[1];

				file = new File(uploadDir+fileNm);
				String url = viewUrl+fileNm;
				category.setLogoUrl(url);
				
				if(! file.isDirectory()){	//해당 폴더가 없을 경우 폴더 생성
					new File(uploadDir).mkdirs();
				}
				logoFile.transferTo(file);
			}
			
			category = categoryDao.update(category);
		} catch (Exception e) {
			// TODO: handle exception
			
			//업로드 파일 삭제
			if(file != null){
				file.delete();
			}
			
			throw e;
		}

		return category;
	}

	@Override
	public int remove(Map<String, Object> condition) throws Exception {
		// TODO Auto-generated method stub
		return categoryDao.delete(condition);
	}

	@Override
	public String findbyChkDupl(Map<String, Object> condition) throws Exception {
		// TODO Auto-generated method stub
		
		String result = "true";
		Integer cnt = (Integer) (categoryDao.SelectListTotalCnt(condition));
		if(cnt != null && cnt == 0){
			result = "false";
		}
		
		return result;
	}

	@Override
	public List<Content> findbyListInCont(Map<String, Object> condition) throws Exception {
		// TODO Auto-generated method stub
		return (List<Content>)(categoryDao.SelectListInCont(condition));
	}
	
	@Override
	public Map<String, Object> findbyListPagingInCont(Map<String, Object> condition)
			throws Exception {
		// TODO Auto-generated method stub
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("contents", (List<Content>) (categoryDao.SelectListInCont(condition)));
		resultMap.put("contentsCnt", (Integer) (categoryDao.SelectListInContTotalCnt(condition)));
		
		return resultMap;
	}

	@Override
	public List<Content> findbyListOutCont(Map<String, Object> condition)
			throws Exception {
		// TODO Auto-generated method stub
		return (List<Content>)(categoryDao.SelectListOutCont(condition));
	}

	@Override
	public Integer addDispOrder(Map<String, Object> condition) throws Exception {
		// TODO Auto-generated method stub
		int result = 0;
		Integer cIdx = (Integer)condition.get("cIdx");
		Integer categoryIdx = (Integer)condition.get("categoryIdx");
		int[] dispOrderList = (int[])condition.get("dispOrderList");
		
		//기존에 등록된 목록 삭제
		categoryDao.deleteDispOrder(condition);
		
		//등록
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("categoryIdx", categoryIdx);
		
		for (int i=0;i<dispOrderList.length;i++) {
			int contentIdx = dispOrderList[i];
			map.put("cIdx", cIdx);
			map.put("contentIdx", contentIdx);
			map.put("dispOrder", i);
			
			result = categoryDao.insertDispOrder(map);
		}
		return result;
	}

	@Override
	public Integer removeDispOrder(Map<String, Object> condition) throws Exception {
		// TODO Auto-generated method stub
		return (Integer)(categoryDao.deleteDispOrder(condition));
	}

}